package co.yixiang.security.service;

import co.yixiang.exception.BadRequestException;
import co.yixiang.security.security.vo.JwtUser;
import co.yixiang.hw.service.YxUserService;
import co.yixiang.hw.service.dto.YxUserDto;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;

/**
 * @author Zheng Jie
 * @date 2018-11-22
 */
@Service("userDetailsService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserDetailsServiceImpl implements UserDetailsService {

    private final YxUserService userService;


    public UserDetailsServiceImpl(YxUserService userService) {
        this.userService = userService;
    }

    @Override
    public UserDetails loadUserByUsername(String username){
        YxUserDto user = userService.finByUserName(username);
        if (user == null) {
            throw new BadRequestException("账号不存在");
        } else {
            if (user.getStatus() == 0) {
                throw new BadRequestException("账号禁止登陆");
            }
            return createJwtUser(user);
        }
    }

    private UserDetails createJwtUser(YxUserDto user) {
        return new JwtUser(
                user.getUid(),
                user.getUsername(),
                user.getNickname(),
                user.getSex().toString(),
                user.getPassword(),
                user.getAvatar(),
                user.getPhone(),
                true,
                new Timestamp(user.getAddTime())
        );
    }
}
